#ifndef _VECTOR_H_
#define _VECTOR_H_

#include <iostream>
#include <assert.h>
using namespace std;

template <class T>
class Vector
{
public:
	//Vector迭代器的原生指针
	typedef T* iterator;
	//const迭代器
	typedef const T* const_iterator;

	iterator begin()
	{
		return _start;
	}
	iterator end()
	{
		return _finish;
	}
	const_iterator cbegin() const
	{
		return _start;
	}
	const_iterator cend() const
	{
		return _finish;
	}
	
	//构造函数
	Vector()
	{
		_start=nullptr;
		_finish=nullptr;
		_end_of_storage=nullptr;
	}

	//复制构造函数
	Vector(const Vector<int>& v):_start(nullptr),_finish(nullptr), _end_of_storage(nullptr)
	{
		Reserve(v.Capacity());
		iterator it = begin();
		const_iterator vit = v.cbegin();
		while (vit != v.cend())
		{
			*it++ = *vit++;
		}
		_finish = _start + v.Size();
		_end_of_storage = _start + v.Capacity();
	}

	//析构函数
	~Vector()
	{
		if (_start)
		{
			delete[] _start;	//释放_start指向的内存
			_start = _finish = _end_of_storage = nullptr;
		}
	}

	//在Vector中任意位置前插入一个数
	void Insert(iterator pos, const T& x)
	{
		assert(pos <= _finish);
		size_t posindex = pos - _start;
		if (_finish == _end_of_storage)
		{
			size_t newcapacity = Capacity() == 0 ? 2 : Capacity() * 2;
			Reserve(newcapacity);
			pos = _start + posindex;
		}
		iterator end = _finish;
		while (end > pos)
		{
			*end = *(end - 1);
			--end;
		}
		*pos = x;
		++_finish;
	}

	//删除Vector任意位置中的数
	iterator Erase(iterator pos)
	{
		iterator begin = pos;
		while (pos != _finish)
		{
			*pos = *(pos + 1);
				++pos;
		}
		--_finish;
		return begin;
	}

	//PushBack实现（往Vector中插入数据）
	void PushBack(const T& x)
	{
		Insert(end(), x);
	}

	//PopBack实现（在Vector后插入数据）
	void PopBack()
	{
		assert(Size() > 0);
		--_finish;
	}

	//实现clear
	void clear()
	{
		while(begin()!=end())
		{
			Erase(end());
		}
	}

	//实现at
	T at(T pos)
	{
		return _start[pos];
	}

	//实现[]访问Vector
	T& operator [](size_t pos)
	{
		assert(pos < Size());
		return _start[pos];
	}

	//增容Capacity
	void Reserve(size_t n) 
	{
		if (n > Capacity())
		{
			size_t size = Size();
			T* tmp = new T[n];
			if (_start)
			{
				//memcpy(tmp, _start, sizeof(T)*size);
				for (size_t i = 0; i < size; ++i)
				{
					tmp[i] = _start[i];
				}
			}
			_start = tmp;
			_finish = _start + size;
			_end_of_storage = _start + n;
		}
	}
	
	size_t Size() const
	{
		return _finish - _start;
	}
	
	size_t Capacity() const
	{
		return _end_of_storage - _start;
	}
	
private:
	//给每个成员都赋上缺省值
	iterator _start = nullptr;
	iterator _finish = nullptr;
	iterator _end_of_storage = nullptr;

};


#endif
